# ///////////////////////////////////////////////////////////////
#
# BY: WANDERSON M.PIMENTA
# PROJECT MADE WITH: Qt Designer and PySide6
# V: 1.0.0
#
# This project can be used freely for all uses, as long as they maintain the
# respective credits only in the Python scripts, any information in the visual
# interface (GUI) can be modified without any implication.
#
# There are limitations on Qt licenses if you want to use your products
# commercially, I recommend reading them on the official website:
# https://doc.qt.io/qtforpython/licenses.html
#
# ///////////////////////////////////////////////////////////////

# MAIN FILE
# ///////////////////////////////////////////////////////////////
from main import *
from PySide6.QtCore import Signal,QElapsedTimer
import pandas
import random
import json
import hashlib
import time
import requests
# import aiohttp
# import asyncio
# from multiprocessing import Process,Queue
# WITH ACCESS TO MAIN WINDOW WIDGETS
# ///////////////////////////////////////////////////////////////
class AppFunctions(MainWindow):
    def setThemeHack(self):
        Settings.BTN_LEFT_BOX_COLOR = "background-color: #495474;"
        Settings.BTN_RIGHT_BOX_COLOR = "background-color: #495474;"
        Settings.MENU_SELECTED_STYLESHEET = MENU_SELECTED_STYLESHEET = """
        border-left: 22px solid qlineargradient(spread:pad, x1:0.034, y1:0, x2:0.216, y2:0, stop:0.499 rgba(255, 121, 198, 255), stop:0.5 rgba(85, 170, 255, 0));
        background-color: #566388;
        """

        # SET MANUAL STYLES
        self.ui.lineEdit.setStyleSheet("background-color: #6272a4;")
        self.ui.pushButton.setStyleSheet("background-color: #6272a4;")
        self.ui.plainTextEdit.setStyleSheet("background-color: #6272a4;")
        self.ui.tableWidget.setStyleSheet("QScrollBar:vertical { background: #6272a4; } QScrollBar:horizontal { background: #6272a4; }")
        self.ui.scrollArea.setStyleSheet("QScrollBar:vertical { background: #6272a4; } QScrollBar:horizontal { background: #6272a4; }")
        self.ui.comboBox.setStyleSheet("background-color: #6272a4;")
        self.ui.horizontalScrollBar.setStyleSheet("background-color: #6272a4;")
        self.ui.verticalScrollBar.setStyleSheet("background-color: #6272a4;")
        self.ui.commandLinkButton.setStyleSheet("color: #ff79c6;")
class UpdataThread(QThread):
    ''' type = 'getall'/'getallsource'/'netbalance' '''
    th_signal = Signal(list)
    th_signal = Signal(str)

    # url = 'http://222.174.233.74:19999/scada/admin-api/real/'
    url = Settings.APPURL
    def __init__(self,model:QStandardItemModel,view:QTableView,proxymodel:NumericSortProxyModel,type:str='getallsource'):
        super().__init__()
        self.url+=type
        self.model = model
        self.view = view
        self.proxymodle = proxymodel
        self.usergroup = []
    def run(self):
        l = self.get_data()
        self.th_signal.emit(l)
    def get_data(self)->list:
        res = requests.get(url=self.url,json=self.usergroup)
        # data = res.json()
        data = res.text
        return data
    def modify_usergroup(self,id):
        res = requests.get(url=Settings.APPURL+f'group/{id}').json()
        self.usergroup = res
        self.start()



class UserAlarm(QThread):
    alarm_signal = Signal(list)
    def __init__(self,mainwindow:QMainWindow):
        super().__init__()
        self.mainwindow = mainwindow
        self.alarm_group = {}


    def run(self):

        self.alarm_signal.emit(self.check_alarm())
        
    def set_alarm_group(self):
        self.alarm_group = self.mainwindow.user_init.get('alarm_group')
        self.username = self.mainwindow.user_init.get('username')
        self.alarm_enable = self.mainwindow.user_init.get('alarm_enable')
    def check_alarm(self):
        # 服务器检测报警，客户但将需要检测的报警点发送给服务器
        # print(self.alarm_group,self.mainwindow.user_init.get('alarm_enable'))
        if  self.mainwindow.user_init.get('alarm_enable') :
            data = {}
            data['alarmgroup'] = self.mainwindow.user_init.get('alarm_group')
            data["username"] = self.mainwindow.user_init.get('username')
            # print(data)
            res = requests.post(url=Settings.APPURL+'/checkalarm',json=data).json()

            # 服务器收到后组织数据，如果有报警，就返回报警点
            if res.get('status')=='none':
                return None
            l = []
            for i in res.get('alarm_data').items():
                l2 = list(i[1].values())
                l.append(l2)
            return l
        return None

class CenterProcessThread(QThread):
    """四个中心站的工艺流程图更新线程"""
    def __init__(self,mainwindow:QMainWindow):
        self.mainwindow = mainwindow
        # pass
        self.timer = QTimer()
        self.timer.setInterval(10000)
        self.timer.timeout.connect(self.run)
        self.timer.start()

    def run(self):
        self.myfunc()
    def myfunc(self):
        res = requests.get(Settings.APPURL+f"/getcenter").json()
        data:dict = res.get('data')
        # var_name:dict = res.get('var_name')
        # var_name_list = list(var_name.items())
        # l = self.findChildren(QLabel,QRegularExpression('jgybe_'))
        # [277,278,279,280]
        center_list = [("System2:100277","guoji"),("System2:100278","youju"),("System2:100279","yaguang"),("System2:100280","tianhong")]
        process_var_list = [
            (".ValueDesc.1.T2h","t2h","二回温度：","℃"),
            (".ValueDesc.1.P2h","p2h","二回压力：","MPa"),
            (".ValueDesc.1.HM_F2","wm_ssll","瞬时流量：","T/h"),
            (".ValueDesc.1.HM_FT2","wm_ljll","累计流量：","T"),
            (".ValueDesc.1.T1g","t1g","一供温度：","℃"),
            (".ValueDesc.1.P1g","p1g","一供压力：","MPa"),
            (".ValueDesc.1.T2g","t2g","二供温度：","℃"),
            (".ValueDesc.1.P2g","p2g","二供压力：","MPa"),
            # (".ValueDesc.1.WM_F2","bswm_ssll","瞬时流量：","T/h"),
            # (".ValueDesc.1.WM_FT2","bswm_ljll","累计流量：","T"),
            (".ValueDesc.1.WM_F2","bs_ssll","瞬时流量：","T/h"),
            (".ValueDesc.1.WM_FT2","bs_ljll","累计流量：","T"),
            (".ValueDesc.1.T1h","t1h","一回温度：","℃"),
            (".ValueDesc.1.P1h","p1h","一回压力：","MPa"),
            (".ValueDesc.1.XP1_SV","f_set1","设定频率1：","Hz"),
            (".ValueDesc.1.XP2_SV","f_set2","设定频率2：","Hz"),
            (".ValueDesc.1.XP1_Hz","f_res1","反馈频率1：","Hz"),
            (".ValueDesc.1.XP2_Hz","f_res2","反馈频率2：","Hz"),
            (".ValueDesc.1.CV1_SV","set","给定开度：","%"),
            (".ValueDesc.1.CV1_U","res","反馈开度：","%"),
            (".ValueDesc.1.HM_H1","hm_ssrl","瞬时热量：","Gj/h"),
            (".ValueDesc.1.HM_HT1","hm_ljrl","累计热量：","Gj"),
            (".ValueDesc.1.HM_F1","hm_ssll","瞬时流量：","T/h"),
            (".ValueDesc.0.L","yw","水箱液位：","m"),
            (".ValueDesc.1.HM_FT1","hm_ljll","累计流量：","T"),
            (".ValueDesc.0.Ep","kwh","站内有功电度：","kWh"),
            (".ValueDesc.1.P1_Filter_Out","p1g_h","污后压力：","MPa"),
            (".ValueDesc.1.P2_Pump_CYC_Out","p2h_pump","出口压力：","MPa"),
            (".ValueDesc.1.P2_Filter_Out","p2h_h","二回后压力：","MPa")


         ]
        for i,j in center_list:
            center_data = data.get(i)
            for v_var,t_pro,k_txt,unit in process_var_list:

                obj = self.mainwindow.findChild(QLabel,j+'_'+t_pro)
                # print(obj.text(),data.get(sysid+v_var))
                if obj:
                    obj.setText(k_txt+f"{center_data.get(i+v_var):.2f} {unit}")
            obj = self.mainwindow.findChild(QLabel,j+'_station_no')
            # print(data.get(sysid+'.StaticInfo.StationName'),data.get(sysid+'.ValueDesc.'+str(sysnum)+'.SEC_NAME'))
            obj.setText(i+"-"+center_data.get(i+'.StaticInfo.StationName')+"-"+center_data.get(i+'.ValueDesc.1.SEC_NAME')+"\n")
            obj.setText(obj.text()+"网络"+center_data.get(i+'.isonline')+" "+center_data.get(i+'.update_time'))
            obj.setStyleSheet("font: 9pt \"Microsoft YaHei UI\";")
        
class ProcessThread(QThread):
    """单独站点的工艺流程图更新线程"""
    def __init__(self,station_num:str,mainwindow:QMainWindow,station_tran_name:str):
        self.station_num = station_num
        self.mainwindow = mainwindow
        self.station_tran_name = station_tran_name
        # pass
        self.timer = QTimer()
        self.timer.setInterval(30000)
        self.timer.timeout.connect(self.run)
        self.timer.start()

    def run(self):
        # print("run")
        self.myfunc()
    def myfunc(self):
        sysnum = self.station_num[-1:]
        sysid = self.station_num[:-1]
        res = requests.get(Settings.APPURL+f"/getone/{self.station_num}").json()
        data:dict = res.get('data')
        var_name:dict = res.get('var_name')
        var_name_list = list(var_name.items())
        # l = self.findChildren(QLabel,QRegularExpression('jgybe_'))
        process_var_list = [
            (".ValueDesc.1.T2h","t2h","二回温度：","℃"),
            (".ValueDesc.1.P2h","p2h","二回压力：","MPa"),
            (".ValueDesc.1.HM_F2","wm_ssll","瞬时流量：","T/h"),
            (".ValueDesc.1.HM_FT2","wm_ljll","累计流量：","T"),
            (".ValueDesc.1.T1g","t1g","一供温度：","℃"),
            (".ValueDesc.1.P1g","p1g","一供压力：","MPa"),
            (".ValueDesc.1.T2g","t2g","二供温度：","℃"),
            (".ValueDesc.1.P2g","p2g","二供压力：","MPa"),
            (".ValueDesc.1.WM_F2","bswm_ssll","瞬时流量：","T/h"),
            (".ValueDesc.1.WM_FT2","bswm_ljll","累计流量：","T"),
            (".ValueDesc.1.T1h","t1h","一回温度：","℃"),
            (".ValueDesc.1.P1h","p1h","一回压力：","MPa"),
            (".ValueDesc.1.XP1_SV","f_set1","设定频率1：","Hz"),
            (".ValueDesc.1.XP2_SV","f_set2","设定频率2：","Hz"),
            (".ValueDesc.1.XP1_Hz","f_res1","反馈频率1：","Hz"),
            (".ValueDesc.1.XP2_Hz","f_res2","反馈频率2：","Hz"),
            (".ValueDesc.1.CV1_SV","set","给定开度：","%"),
            (".ValueDesc.1.CV1_U","res","反馈开度：","%"),
            (".ValueDesc.1.HM_H1","hm_ssrl","瞬时热量：","Gj/h"),
            (".ValueDesc.1.HM_HT1","hm_ljrl","累计热量：","Gj"),
            (".ValueDesc.1.HM_F1","hm_ssll","瞬时流量：","T/h"),
            (".ValueDesc.0.L","yw","水箱液位：","m"),
            (".ValueDesc.1.HM_FT1","hm_ljll","累计流量：","T"),
            (".ValueDesc.0.Ep","kwh","站内有功电度：","kWh"),
            
            (".ValueDesc.1.P1_Filter_Out","p1g_h","一供后压力：","MPa"),

            (".ValueDesc.1.CV2_SV","set_pt","给定开度：","%"),
            (".ValueDesc.1.CV2_U","res_pt","反馈开度：","%"),

            (".ValueDesc.1.P2_Filter_Out","p2h_h","二回后压力：","MPa"),
            (".ValueDesc.1.P2_Pump_CYC_Out","p2h_pump","出口压力：","MPa"),

            (".ValueDesc.1.CV1h_U","set_h","给定开度：","%"),
            (".ValueDesc.1.CV1h_SV","res_h","给定开度：","%")

         ]
        for v_var,t_pro,k_txt,unit in process_var_list:

            obj = self.mainwindow.findChild(QLabel,self.station_tran_name+'_'+t_pro)
            # print(obj.text(),data.get(sysid+v_var))
            if obj:
                s = f".{sysnum}."
                v_var = v_var.replace(".1.",s)
                obj.setText(k_txt+f"{data.get(sysid+v_var):.2f} {unit}")
        obj:QLabel = self.mainwindow.findChild(QLabel,self.station_tran_name+'_station_no')
        obj.setStyleSheet("font: 9pt \"Microsoft YaHei UI\";")
        # print(data.get(sysid+'.StaticInfo.StationName'),data.get(sysid+'.ValueDesc.'+str(sysnum)+'.SEC_NAME'))
        obj.setText(self.station_num+"-"+data.get(sysid+'.StaticInfo.StationName')+"-"+data.get(sysid+'.ValueDesc.'+str(sysnum)+'.SEC_NAME')+"\n")
        if data.get(sysid+'.isonline')=='异常':
            # obj.setForegroundRole(QColor('red'))
            # print(obj.styleSheet())
            obj.setStyleSheet(obj.styleSheet()+'color: rgb(255, 0, 0);')
        obj.setText(obj.text()+"网络"+data.get(sysid+'.isonline')+" "+data.get(sysid+'.update_time'))
        
        
        
class Weather(QThread):
    """天气预报更新线程"""
    def __init__(self,mainwindow:QMainWindow):
        self.mwindow = mainwindow
        self.t = QTimer()
        self.t.setInterval(1000*60*30)
        self.t.timeout.connect(self.run)
        self.t.start()
        self.url = "http://182.40.104.249:9005"
    def run(self):
        # print('update_weather')
        self.get_weather()
        self.get_forecast()
    def get_weather(self):
        url = self.url+"/weather/now"
        res = requests.get(url=url)
        weather_list = [("update_time","更新时间: ",""),
         ("pre_1h","过去1小时降水量: "," mm"),
         ("prs","气压: "," hPa"),
         ("rhu","相对湿度: "," %"),
         ("tem","温度/气温: "," ℃"),
         ("tem_min","最低温度: "," ℃"),
         ("vis","能见度(人工): "," m"),
         ("vis_min","最小能见度: "," m"),
         ("wep_now","现在天气: ",""),
         ("win_s_max","最大风速: "," m/s"),
         ("tem_max","最高温度: "," ℃")]
        if res.status_code ==200:
            # print(res.json())
            data = res.json()
            for i,j,k in weather_list:
                obj = self.mwindow.findChild(QLabel,"weather_"+i)
                if obj:
                    obj.setText(j+data.get(i)+k)

    def get_forecast(self):
        url = self.url+"/weather/forecast"
        res:list = requests.get(url=url).json()
        res.reverse()
        
        model = QStandardItemModel()
        for i in res:
            model.appendRow([QStandardItem(i.get('forecastdate')),
                             QStandardItem(i.get('weather')),
                             QStandardItem(i.get('temperature')),
                             QStandardItem(str(i.get('totalcloudcover'))),
                             QStandardItem(str(i.get('avgwindlevel'))),
                             QStandardItem(i.get('winddirectiontext') if i.get('winddirectiontext') else ''),
                             QStandardItem(i.get('humidity')),
                             QStandardItem(i.get('visibility')),
                             ])
        header_list = ['预报时间',
                       '天气现象',
                       '温度/℃',
                       '总云量',
                       '风力等级',
                       '风向',
                       '湿度',
                       '能见度(km)',
                    
                       ]
                       
        model.setHorizontalHeaderLabels(header_list)
        self.mwindow.ui.tv_weather_forcast.setModel(model)
        self.mwindow.ui.tv_weather_forcast.resizeColumnToContents(0)
        # self.mwindow.ui.tv_weather_forcast.set

